import random

from flask_restful import Resource, reqparse
import requests
import json
from huiyan.extions import cache


# 参数解析
parser = reqparse.RequestParser()
parser.add_argument('image', type=str, default='')
parser.add_argument('type', type=str, default='base64')

# 百度OCR
class baiduOCR(Resource):
    def post(self):
        args = parser.parse_args()
        image: str = args.get('image')
        type: str = args.get('type')

        url = "https://cloud.baidu.com/aidemo"

        # 判断图片还是Base64数据
        if type == "base64":
            payload = {
                "type": "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic",
                "detect_direction": "false",
                "language_type": "CHN_ENG",
                "image": image
            }
        else:
            payload = {
                "type": "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic",
                "detect_direction": "false",
                "language_type": "CHN_ENG",
                "image_url": image
            }

        # 构建请求头
        headers = {
            'Cookie': f'CURRENT_PAGE=/product/ocr/general; BAIDUID=E4F6C300C3AF554E1{str(random.random())[-5:-1]}05B8E55{str(random.random())[-5:-1]}; BAIDU_CLOUD_TRACK_PATH=https%3A%2F%2Fcloud.baidu.com%2Fproduct%2Focr%2Fgeneral; Hm_lvt_28a17f66627d87f1d046eae152a1c93d=1683539313; Hm_lpvt_28a17f66627d87f1d046eae152a1c93d=1683539313; AGL_USER_ID=fa6c{str(random.random())[-5:-1]}-cf44-4c2d-8f46-0c52dc{str(random.random())[-5:-1]}ce',
            'Referer': 'https://cloud.baidu.com/product/ocr/general',
            "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/112.0'
        }

        # 设置代理服务器的地址和端口号
        # proxies = {
        #     'http': '211.97.2.196:9002',
        #     'http': '183.221.242.102:9443',
        # }
        proxy = self.get_proxy()

        # 请求数据
        for i in range(32):
            try:
                response = requests.request("POST", url, headers=headers, proxies={"http": "http://{}".format(proxy)}, data=payload)
                data_ = json.loads(response.text)
                if data_['errno'] != 0:
                    # print(f'{response.text}')
                    print(f'请求失败{i + 1}')
                    continue
                break
            except Exception as e:
                # print(f'{response.text}')
                print(f'请求失败{i + 1}')
                print(f"An error occurred: {e}")

                if i == 31:
                    return {
                        "status": 400,
                        "msg": '服务器请求错误,请重试'
                    }
                continue


        # cache.set(Req.url, data_, timeout=60 * 60 * 24)
        return data_

    def get_proxy(self):
        # return requests.get("http://demo.spiderpy.cn/get/?type=https").json()
        return requests.get("https://www.docip.net/data/free.json").json()["data"]
        # random_value = random.choice(arr)
        # return random_value['ip']
